package com.example.shell.config;

import cn.hutool.core.util.ObjectUtil;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

public class FileConfig {

    private static final String[] PATH = new String[]{"C:\\Users\\"+System.getProperty("user.name")+"\\.oa\\config.txt"};
    private static final Properties PROP = new Properties();

    public FileConfig(){
        init();
    }

    public FileConfig(String path){
        PATH[0] = path;
        init();
    }

    private void init(){
        if (!new File(PATH[0]).exists()){
            createIfNotExists(PATH[0]);
            write();
        }else {
            read();
        }
    }

    public void set(String key,String value){
        PROP.put(key,value);
    }
    public String get(String key){
        if (ObjectUtil.isNull(PROP.get(key))){
            return "";
        }
        return (String)PROP.get(key);
    }

    public void read() {
        try {
            InputStream input = Files.newInputStream(Paths.get(PATH[0]));
            PROP.load(input);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void write() {
        try {
            FileOutputStream output = new FileOutputStream(PATH[0]);
            PROP.store(output, "oa shell 系统配置文件");
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
//        try {
//            FileConfig config = new FileConfig();
//            config.set("oa","oa");
//            config.write();
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        String username = System.getProperty("user.name");
        System.out.println("当前登录用户: " + username);

    }

    private void createIfNotExists(String filePath){
        File file = new File(filePath);

        if (!file.getParentFile().exists()) {
            // 如果目录不存在，创建目录
            boolean directoryCreated = file.getParentFile().mkdirs();
            if (!directoryCreated) {
                System.out.println("Failed to create directory.");
                return;
            }
        }

        try {
            // 创建文件
            boolean fileCreated = file.createNewFile();
            if (fileCreated) {
                System.out.println("File created successfully: " + file.getAbsolutePath());
            } else {
                System.out.println("Failed to create file.");
            }
        } catch (IOException e) {
            System.out.println("An error occurred while creating the file: " + e.getMessage());
        }
    }
}
